package com.daily.daily_push.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.List;

import okhttp3.Credentials;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

public class HarborClient {
    private String baseUrl;
    private String username;
    private String password;
    private OkHttpClient client;
    private Gson gson;

    public HarborClient(String baseUrl, String username, String password) {
        this.baseUrl = baseUrl;
        this.username = username;
        this.password = password;
        this.client = new OkHttpClient();
        this.gson = new Gson();
    }

    public List<String> getImageTags(String projectName, String repositoryName) throws IOException {
        String url = String.format("%s/api/v2.0/projects/%s/repositories/%s/artifacts?with_tag=true&with_label=false&with_scan_overview=false&with_signature=false&with_immutable_status=false", baseUrl, projectName, repositoryName);
        Request request = new Request.Builder()
                .url(url)
                .addHeader("Authorization", Credentials.basic(username, password))
                .build();
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        System.out.println("======" +responseBody); // 打印返回的 JSON 字符串
        List<Artifact> artifacts = gson.fromJson(responseBody, new TypeToken<List<Artifact>>(){}.getType());
        List<String> tags = new ArrayList<>();
        for (Artifact artifact : artifacts) {
            for (Tag tag : artifact.getTags()) {
                tags.add(tag.getName());
            }
        }
        return tags;
    }

    private static class Artifact {
        private List<Tag> tags;

        public List<Tag> getTags() {
            return tags;
        }

        public void setTags(List<Tag> tags) {
            this.tags = tags;
        }
    }

    private static class Tag {
        private String name;

        public String getName() {
            return name;
        }

        public void setName(String name) {
            this.name = name;
        }
    }


    // 使用示例
    public static void main(String[] args) throws IOException {
        HarborClient client = new HarborClient("http://111.230.74.250", "admin", "H23i8*9po0lk.iuw9");
        List<String> tags = client.getImageTags("zhankuitest", "daily_push");
        System.out.println(tags);
    }

}